<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * @ filename: defined totally fields in user that login
 * @ author: Nguyen Van Nam
 * @ license: Nam & Thien
 * @ contact: nguyennamcdt1@gmail.com || thelightsky@gmail.com
 */

// define some key word 
define('ERR_LOGIN_USERNAME_EMPTY', 1);
define('ERR_LOGIN_PASSWORD_EMPTY', 2);
define('ERR_LOGIN_USERNAME_PASSWORD_WRONG', 3);
define('ERR_LOGIN_USER_INACTIVE', 4);

class Login extends DB_Connect {
    public  $login;
    public  $msg; // message to show
    public  $lid;
    public  $username;
    public  $password;
    private $auth;
    public  $err_msg;

    function __construct($dbo=NULL) {
        
        parent::__construct($dbo);
        $this->username = NULL;
        $this->password = NULL;
        $this->auth     = false;
        $this->msg = array( 'err' => array() );
        $this->lid = '';
        $this->err_msg = '';
    }
    
    public function to_set_username($username) {
        $this->username = trim($username);
    }
    
    public function to_set_password($password) {
        $this->password = trim($password);
    }
    
    public function to_get_session_id(){
        return $this->lid;
    }
    
    public function login() {
        global $lng;
        if(empty ($this->username)) {
            $this->msg['err'][] = ERR_LOGIN_USERNAME_EMPTY;
            $this->err_msg = 'Empty Login';
        } else if(empty ($this->password)) {
            $this->msg['err'][] = ERR_LOGIN_PASSWORD_EMPTY;
            $this->err_msg = 'Empty Password';
        } else {
            $this->authenticate();
        }
        if($this->auth) {
            $this->init_user_session();
        }
        return $this->auth;
    }
    
    public function authenticate() {
        global $config;
        global $mysql;
        if(isset ($this->username) && isset ($this->password)) {
            $username = mysql_escape_string($this->username);
            $password = mysql_escape_string($this->password);
            // encryptted password
            $encrypted_pass = md5($password) ;
            //query DB
            $query = "SELECT *FROM Users WHERE username ='$username' AND password = '$encrypted_pass'";
            $data = $mysql->prepare($query);
            $data->execute();
            $tmp = $data->fetch(PDO::FETCH_ASSOC);
            if( $tmp ) {
                if( empty ($tmp['state'])) {
                    $this->auth = FALSE;
                    $this->msg['err'][] = ERR_LOGIN_USER_INACTIVE;
                    $this->err_msg = 'This account is not still activated';
                } else {
                    $this->auth = true;
                }
            } else {
                $this->auth = false;
                $this->msg['err'][] = ERR_LOGIN_USERNAME_PASSWORD_WRONG; // not get this account
                $this->err_msg = 'Password or Username is wrong';
            }            
        } else {
            $this->to_get_session_id(); // get id in db
            $lid = mysql_escape_string($this->lid);
            $expire = mktime() + $config['sesstion']['expire'];
            $query = "SELECT S.* FROM Sessions S INNER JOIN Users U ON S.username = U.username WHERE lid = '$lid' AND $expire > UNIX_TIMESTAMP(NOW())";
            $sth = $mysql->prepare($query);
            $sth->execute();
            if ($sth->fetch(PDO::FETCH_ASSOC)) {
                    $this->auth = true;
            } else {
                    $this->auth = false;
            }
        }       
        return $this->auth;
    }
    //update to cookie the last time user logins
    private function init_user_session() {
        global $config, $mysql;
        if( $this->auth ) {
            $username = mysql_escape_string($this->username);
            $rand = md5(mt_rand());
            $id = substr($rand, 0, 11);
            $lid = "{$username}_{$rand}";
            $expire = time() + $config['session']['expire'];
            $mysql->exec("DELETE FROM Sessions WHERE username = '$username'");
            $mysql->exec("INSERT INTO Sessions(username, lid, expire) VALUE ('$username', '$lid', $expire)");
            $this->lid = $lid;
            setcookie($config['session']['baseCookie'], $lid, null, $config['session']['baseDir']);
            return true;
        } else {
                return false;
        }
    }
    
    //save the last time login
    public function set_user_session() {
        global $config, $mysql;
        if($this->auth) {
            $lid = mysql_escape_string($this->lid);
            $sth = $mysql->prepare("SELECT * FROM Sessions WHERE lid = '$lid'");            
        } else {
            $this->init_user_session();
        }
    }
    
    public function get_user_session_info() {
        global $config, $mysql;
        if(!$this->auth) {
            return FALSE;
        }
        $lid = mysql_escape_string($this->lid);
        $sth = $mysql->prepare("SELECT U.username, U.id, U.type FROM Users U INNER JOIN Sessions S ON (S.username = U.username) WHERE S.lid = '$lid'");
        $sth->execute();
        if ($sth) {
            $login = $sth->fetch(PDO::FETCH_ASSOC);
            $this->login = $login;
            return $login;
        }
    }
    
    public function log_out() {
        global $config, $mysql;
        $lid = mysql_escape_string($this->lid);
        $username = mysql_escape_string($this->username);
        $mysql->exec("DELETE FROM Sessions WHERE lid = '$lid' OR username = '$username'");
        setcookie($config['session']['baseCookie'],'', time() - 3600 );
    }
    
    public function get_err_msg() {
        return $this->err_msg; // return array error messages
    }
}
?>
